<template>
  <div class="ai-chat">
    <!-- 头部 -->
    <div class="chat-header">
      <div class="header-content">
        <div class="logo">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M12 2C6.48 2 2 6.48 2 12C2 17.52 6.48 22 12 22C17.52 22 22 17.52 22 12C22 6.48 17.52 2 12 2ZM16.2 16.2L11 13V7H12.5V12.2L17 14.9L16.2 16.2Z" fill="#409eff"/>
          </svg>
          <h2>AI 助手</h2>
        </div>
        <button class="clear-btn" @click="clearChat" :class="{ 'active': aiStore.getMessages.length > 0 }">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M6 19C6 20.1 6.9 21 8 21H16C17.1 21 18 20.1 18 19V7H6V19ZM19 4H15.5L14.5 3H9.5L8.5 4H5V6H19V4Z" fill="currentColor"/>
          </svg>
          <span>清空对话</span>
        </button>
      </div>
    </div>

    <!-- 对话区域 -->
    <div class="chat-messages">
      <!-- 初始提示 -->
      <div v-if="aiStore.getMessages.length === 0" class="empty-state">
        <div class="empty-icon">
          <svg width="64" height="64" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M12 2C6.48 2 2 6.48 2 12C2 17.52 6.48 22 12 22C17.52 22 22 17.52 22 12C22 6.48 17.52 2 12 2ZM16.2 16.2L11 13V7H12.5V12.2L17 14.9L16.2 16.2Z" fill="#c0c4cc"/>
          </svg>
        </div>
        <p>开始与 AI 助手对话吧</p>
        <div class="suggestions">
          <span class="suggestion-tag" @click="sendSuggestion('如何使用这个工具？')">如何使用这个工具？</span>
          <span class="suggestion-tag" @click="sendSuggestion('推荐一本好书')">推荐一本好书</span>
          <span class="suggestion-tag" @click="sendSuggestion('解释一下量子计算')">解释一下量子计算</span>
        </div>
      </div>

      <!-- 消息列表 -->
      <div class="chat-messages-inner" ref="messageContainer">
        <div 
          class="message" 
          v-for="msg in aiStore.getMessages" 
          :key="msg.key"
          :class="{ 'message-enter': isNewMessage(msg.key) }"
        >
          <!-- 用户消息 -->
          <div v-if="msg.role === 'user'" class="user-message">
            <div class="message-content">
              <div class="content">{{ msg.content }}</div>
            </div>
            <div class="avatarUser">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M12 12C14.21 12 16 10.21 16 8C16 5.79 14.21 4 12 4C9.79 4 8 5.79 8 8C8 10.21 9.79 12 12 12ZM12 6C13.1 6 14 6.9 14 8C14 9.1 13.1 10 12 10C10.9 10 10 9.1 10 8C10 6.9 10.9 6 12 6ZM12 14C9.33 14 4 15.34 4 17V20H20V17C20 15.34 15.67 14 12 14ZM6 18V17C6 16.55 8.67 15.64 12 15.64C15.33 15.64 18 16.55 18 17V18H6ZM15 9H9V7H15V9Z" fill="white"/>
              </svg>
            </div>
          </div>

          <!-- AI 消息（流式更新） -->
          <div v-else class="ai-message">
            <div class="avatar">AI</div>
            <div class="message-content">
              <!-- 关键：使用v-text实时更新内容，支持HTML格式 -->
              <div class="content" v-text="msg.content"></div>
              <div class="message-meta">
                <span class="time">{{ formatTime(msg.timestamp) }}</span>
                <button class="copy-btn" @click="copyMessage(msg.content)">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M16 11C17.66 11 18.99 9.66 18.99 8C18.99 6.34 17.66 5 16 5C14.34 5 13 6.34 13 8C13 9.66 14.34 11 16 11ZM16 7C16.55 7 17 7.45 17 8C17 8.55 16.55 9 16 9C15.45 9 15 8.55 15 8C15 7.45 15.45 7 16 7ZM16 13C13.67 13 8 14.17 8 16V19H20V16C20 14.17 14.33 13 16 13ZM10 18H12V16C12.31 15.91 15.68 15 16 15C16.32 15 19.69 15.91 20 16V18H18V17C18 16.45 15.67 15.6 12 15.6C8.33 15.6 6 16.45 6 17V18H8V17C8 16.72 9.22 16 12 16C14.78 16 16 16.72 16 17C16 17.28 14.78 18 12 18H10ZM3 7C3 4.79 4.79 3 7 3H17C19.21 3 21 4.79 21 7V13.8C20.39 13.45 19.72 13.2 19 13.08V7C19 5.9 18.1 5 17 5H7C5.9 5 5 5.9 5 7V19C5 20.1 5.9 21 7 21H13.08C13.2 21.72 13.45 22.39 13.8 23H7C4.79 23 3 21.21 3 19V7Z" fill="#888"/>
                  </svg>
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载中（流式响应结束前一直显示） -->
        <div v-if="aiStore.isLoading" class="loading">
          <div class="loader"></div>
          <p>AI 正在思考...</p>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input">
      <div class="input-container">
        <input
          type="text"
          v-model="inputText"
          placeholder="输入消息..."
          @keyup.enter="sendMessage"
          :disabled="aiStore.isLoading"
          @focus="inputFocused = true"
          @blur="inputFocused = false"
        />
        <button
          class="send-btn"
          @click="sendMessage"
          :disabled="!inputText.trim() || aiStore.isLoading"
        >
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M2.05 13H21.95L18.5 16.45L19.95 17.9L24 13L19.95 8.1L18.5 9.55L21.95 13H2.05L5.5 9.55L4.05 8.1L0 13L4.05 17.9L5.5 16.45L2.05 13Z" fill="white"/>
          </svg>
        </button>
      </div>
      <div class="input-hint" v-if="!inputText.trim() && !aiStore.isLoading">
        <span>按 Enter 发送，Shift+Enter 换行</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, onMounted } from "vue";
import { useAiMessageStore1 } from "../../stores/aiPinia/aiConversation";
import { useUserStore } from "@/stores";

// 状态管理
const aiStore = useAiMessageStore1();
const userStore = useUserStore();
const inputText = ref("");
const messageContainer = ref<HTMLDivElement>(null);
const inputFocused = ref(false);
const lastMessageKey = ref("");

// 处理用户ID
const userids = userStore.currentUser?.userId || "0";
const userid = userids.toString();

// 格式化时间
const formatTime = (timestamp: number) => {
  if (!timestamp) return "";
  const date = new Date(timestamp);
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 发送建议消息
const sendSuggestion = (text: string) => {
  inputText.value = text;
  sendMessage();
};

// 复制消息（改进版本）
const copyMessage = (content: string) => {
  // 方法1：尝试 clipboard API（现代浏览器优先）
  if (navigator.clipboard) {
    navigator.clipboard.writeText(content)
      .then(showCopySuccess)
      .catch(() => fallbackCopy(content)); // 失败时用备用方法
  } else {
    // 方法2：备用方案（兼容旧浏览器）
    fallbackCopy(content);
  }
};

// 显示复制成功提示
const showCopySuccess = () => {
  const temp = document.createElement('div');
  temp.className = 'copy-toast';
  temp.textContent = '已复制到剪贴板';
  document.body.appendChild(temp);
  setTimeout(() => temp.remove(), 2000);
};

// 备用复制方法：创建临时文本框选中复制
const fallbackCopy = (content: string) => {
  const textarea = document.createElement('textarea');
  textarea.value = content;
  // 隐藏临时文本框（不影响页面布局）
  textarea.style.position = 'fixed';
  textarea.style.left = '-9999px';
  document.body.appendChild(textarea);
  
  // 选中并复制
  textarea.select();
  document.execCommand('copy'); // 旧版复制API
  document.body.removeChild(textarea);
  
  showCopySuccess();
};

// 检测是否为新消息（用于动画）
const isNewMessage = (key: string) => {
  const isNew = key === lastMessageKey.value;
  if (isNew) {
    // 动画结束后清除标记
    setTimeout(() => {
      lastMessageKey.value = "";
    }, 300);
  }
  return isNew;
};

// 自动滚动到底部（核心优化：支持流式更新时实时滚动）
const scrollToBottom = () => {
  nextTick(() => {
    if (messageContainer.value) {
      // 平滑滚动到最底部
      messageContainer.value.scrollTo({
        top: messageContainer.value.scrollHeight,
        behavior: 'smooth' // 平滑滚动，避免跳动
      });
    }
  });
};

// 监听消息内容变化（核心：深度监听消息内容，支持流式更新）
watch(
  () => aiStore.getMessages.map(msg => msg.content), // 监听所有消息的content变化
  (newContents, oldContents) => {
    // 只有当内容确实变化时才滚动（避免重复触发）
    if (newContents.length > 0 && newContents.join('') !== oldContents.join('')) {
      scrollToBottom();
    }
  },
  { deep: true, immediate: false } // 深度监听，内容变化立即触发
);

// 监听消息列表长度变化（新消息添加时）
watch(
  () => aiStore.getMessages.length,
  (newLen, oldLen) => {
    if (newLen > oldLen) {
      // 记录最新消息的key，用于动画
      const lastMsg = aiStore.getMessages[newLen - 1];
      lastMessageKey.value = lastMsg.key;
      scrollToBottom();
    }
  }
);

// 发送消息
const sendMessage = async () => {
  const text = inputText.value.trim();
  if (!text || aiStore.isLoading) return;
  
  const timestamp = new Date().getTime();
  // 发送前清空输入框（优化体验）
  inputText.value = "";
  
  try {
    // 调用Pinia方法发送消息，触发流式响应
    // 假设sendMessageToAI会通过WebSocket/SSE接收流式数据，并实时更新message.content
    await aiStore.sendMessageToAI( text,userid);
  } catch (error) {
    console.error("发送失败:", error);
  }
};

// 清空对话
const clearChat = () => {
  if (aiStore.getMessages.length > 0 && confirm("确定要清空所有对话吗？")) {
    aiStore.clearMessages();
  }
};

// 初始化样式（添加复制提示样式）
onMounted(() => {
  const style = document.createElement('style');
  style.textContent = `
    .copy-toast {
      position: fixed;
      bottom: 30px;
      left: 50%;
      transform: translateX(-50%);
      padding: 8px 16px;
      background: #409eff;
      color: white;
      border-radius: 4px;
      font-size: 14px;
      z-index: 9999;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      animation: fadeInOut 2s ease;
    }
    
    @keyframes fadeInOut {
      0% { opacity: 0; transform: translate(-50%, 10px); }
      20% { opacity: 1; transform: translate(-50%, 0); }
      80% { opacity: 1; transform: translate(-50%, 0); }
      100% { opacity: 0; transform: translate(-50%, 10px); }
    }
  `;
  document.head.appendChild(style);
});
</script>

<style scoped>
.ai-chat {
  width: 100%;
  max-width: 600px;
  margin: 20px auto;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  background-color: #fff;
}

/* 头部 */
.chat-header {
  background: #409eff;
  padding: 14px 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
  gap: 8px;
}

.logo h2 {
  margin: 0;
  font-size: 18px;
  color: white;
  font-weight: 500;
}

.clear-btn {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  background: rgba(255, 255, 255, 0.2);
  border: none;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  color: white;
  transition: all 0.2s ease;
  opacity: 0.8;
}

.clear-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  opacity: 1;
}

.clear-btn.active {
  opacity: 1;
}

/* 对话区域 */
.chat-messages {
  height: 500px;
  background-color: #fafafa;
  position: relative;
}

.chat-messages-inner {
  height: 100%;
  overflow-y: auto;
  padding: 20px;
  scroll-behavior: smooth; /* 平滑滚动 */
  user-select: text; /* 添加这一行 */
}

/* 滚动条美化 */
.chat-messages-inner::-webkit-scrollbar {
  width: 6px;
}

.chat-messages-inner::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

.chat-messages-inner::-webkit-scrollbar-thumb {
  background: #ddd;
  border-radius: 10px;
}

.chat-messages-inner::-webkit-scrollbar-thumb:hover {
  background: #ccc;
}

/* 初始状态 */
.empty-state {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  padding: 20px;
  text-align: center;
}

.empty-icon {
  margin-bottom: 16px;
  opacity: 0.6;
}

.empty-state p {
  margin: 0 0 24px 0;
  font-size: 16px;
}

.suggestions {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: center;
  width: 100%;
  max-width: 400px;
}

.suggestion-tag {
  background-color: white;
  border: 1px solid #eee;
  border-radius: 16px;
  padding: 6px 14px;
  font-size: 14px;
  color: #555;
  cursor: pointer;
  transition: all 0.2s ease;
  white-space: nowrap;
}

.suggestion-tag:hover {
  background-color: #f5f7fa;
  border-color: #e6e9ed;
  color: #409eff;
  transform: translateY(-1px);
}

/* 消息样式 */
.message {
  margin-bottom: 20px;
  animation: fadeIn 0.2s ease-out;
}

/* 新消息动画 */
.message-enter {
  animation: messagePop 0.3s ease-out;
}

@keyframes messagePop {
  from {
    transform: translateY(10px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/* 用户消息 */
.user-message {
  display: flex;
  justify-content: flex-end;
  animation: fadeIn 0.3s ease-out;
}

/* AI消息 */
.ai-message {
  display: flex;
  justify-content: flex-start;
  animation: fadeIn 0.3s ease-out;
}

/* 头像样式 */
.avatar, .avatarUser {
  width: 34px;
  height: 34px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  color: #999;
}

.avatar {
  background-color: #f1f1f1;
  margin-right: 10px;
}

.avatarUser {
  background-color: #409eff;
  margin-left: 10px;
}

/* 消息内容容器 */
.message-content {
  max-width: calc(100% - 50px);
}

/* 气泡样式（支持动态高度） */
.content {
  padding: 10px 14px;
  border-radius: 16px;
  line-height: 1.6;
  font-size: 15px;
  word-wrap: break-word;
  min-height: 20px; /* 避免内容为空时气泡消失 */
}

.user-message .content {
  background-color: #409eff;
  color: white;
  border-bottom-right-radius: 4px;
  box-shadow: 0 1px 2px rgba(64, 158, 255, 0.2);
}

.ai-message .content {
  background-color: white;
  color: #333;
  border: 1px solid #f0f0f0;
  border-bottom-left-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

/* 消息元数据 */
.message-meta {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 4px;
  font-size: 12px;
}

.time {
  color: #999;
  margin-right: 8px;
}

.copy-btn {
  background: none;
  border: none;
  cursor: pointer;
  opacity: 0.6;
  transition: all 0.2s;
  padding: 2px 4px;
  border-radius: 3px;
}

.copy-btn:hover {
  opacity: 1;
  background: rgba(0, 0, 0, 0.05);
}

/* 加载状态 */
.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 16px 0;
  color: #666;
  font-size: 14px;
}

.loader {
  width: 18px;
  height: 18px;
  border: 2px solid #e5e5e5;
  border-top-color: #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-right: 10px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 输入区域 */
.chat-input {
  padding: 12px;
  border-top: 1px solid #f0f0f0;
  background-color: white;
}

.input-container {
  display: flex;
  gap: 10px;
  position: relative;
}

.chat-input input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #e5e5e5;
  border-radius: 24px;
  font-size: 15px;
  outline: none;
  transition: all 0.2s ease;
  resize: none;
  height: 48px;
  line-height: 24px;
}

.chat-input input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
}

.chat-input input::placeholder {
  color: #c0c4cc;
}

.send-btn {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.send-btn:not(:disabled):hover {
  background-color: #66b1ff;
  transform: translateY(-1px);
}

.send-btn:disabled {
  background-color: #f5f5f5;
  color: #ccc;
  cursor: not-allowed;
}

.input-hint {
  position: absolute;
  bottom: -20px;
  left: 20px;
  font-size: 12px;
  color: #999;
  pointer-events: none;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .ai-chat {
    margin: 0;
    border-radius: 0;
    height: 100vh;
    max-width: 100%;
    border: none;
  }

  .chat-messages {
    height: calc(100vh - 160px);
  }

  .content {
    font-size: 14px;
    padding: 9px 13px;
  }

  .chat-header {
    padding: 12px 16px;
  }

  .chat-messages-inner {
    padding: 15px;
  }

  .suggestions {
    gap: 8px;
  }

  .suggestion-tag {
    padding: 5px 12px;
    font-size: 13px;
  }
}
</style>